﻿using FlickrNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WindowsLive.Writer.Api;

namespace FlickrHarmony {
    public static class Security {
		/// <summary>
		/// Verify that profile is authenticated
		/// </summary>
		/// <returns>Boolean indicating success</returns>
		internal static bool Verify(IWin32Window liveWriterWindow) {
			FlickrNet.Auth authorization = null;

			if (!Plugin.Profile.IsEmptyToken) {
				// validate existing token
				using (WaitForm form = new WaitForm()) {
					// prepare form
					form.Label = "Verifying Authentication …";
					form.DoWork += (sender, e) => {
						authorization = Plugin.Flickr.AuthCheckToken(Plugin.Profile.Token);
						if (authorization != null) { Plugin.Profile.Token = authorization.Token; }
					};
					// show form
					if (form.ShowDialog(liveWriterWindow) != DialogResult.OK) { return false; }
				}
			}

			if (Plugin.Profile.IsEmptyToken || (authorization == null)) {
				// if no token then begin the authentication process
				Security.Authenticate(liveWriterWindow);
			}
			return (!Plugin.Profile.IsEmptyToken);
		}

		public static bool Authenticate(IWin32Window liveWriterWindow) {
            string frob;
			FlickrNet.Auth authorization = null;

            using (AuthForm form = new AuthForm()) {
                if (form.ShowDialog(liveWriterWindow) != DialogResult.OK) { return false; }
                frob = form.Frob;
            }

			using (WaitForm form = new WaitForm()) {
				// prepare form
				form.Label = "Awaiting Authentication Response …"; ;
				form.DoWork += (sender, e) => {
					while (!e.Cancel) {
						try {
							authorization = Plugin.Flickr.AuthGetToken(frob);
							if (authorization == null) { Thread.Sleep(2000); } else { break; }
						} catch (FlickrNet.FlickrApiException ex) {
							if (ex.Code == 108) { }
						}
					}
				};
				// show form
				if (form.ShowDialog(liveWriterWindow) != DialogResult.OK) {
					MessageBox.Show(
					   "Authentication has failed. Please try again",
					   "Authentication Failed",
					   MessageBoxButtons.OK,
					   MessageBoxIcon.Error);
					return false;
				}
				if (authorization != null) {
					Plugin.Profile.Token = authorization.Token;
					return true;
				} else {
					return false;
				}
			}
        }
    }
}
